package com.wnxy.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wnxy.dto.LoginDto;
import com.wnxy.dto.QQInfoDto;
import com.wnxy.dto.Result;
import com.wnxy.dto.StatusCode;
import com.wnxy.model.Manager;
import com.wnxy.service.ManagerService;
import com.wnxy.util.DateUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class QQFailureHandler implements AuthenticationFailureHandler {
    private ObjectMapper om=new ObjectMapper();
    private ManagerService managerService=new ManagerServiceImpl();
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        String message=e.getMessage();
        String openId = message.substring(6,message.indexOf("{"));
        String js=message.substring(message.indexOf("{"));
        message = message.substring(0, 6);
        System.out.println(openId);
        System.out.println(js);
        QQInfoDto qq = om.readValue(js, QQInfoDto.class);
        qq.setOpenId(openId);
        Result result = Result.getInstance().setFlag(true).setStatusCode(StatusCode.ERROR.getCode()).setMessage(message).setData(qq);

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf8");
        String json=om.writeValueAsString(result);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("<!DOCTYPE html>").append("<html>").append("<head><meta charset=\"utf-8\"></head>")
                .append("<script>").append("window.opener.postMessage('"+json+"','*')")
                .append("</script>")
                .append("<body>").append("<h3 style='text-align:center'>已绑定</h3>").append("</body></html>");
        response.getWriter().write(om.writeValueAsString(stringBuffer.toString()));
        response.getWriter().flush();
    }
}
